﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class AutoLIR : Form
    {
        public AutoLIR()
        {
            InitializeComponent();
        }
        private void btn_start_Click(object sender, EventArgs e)//开始监听
        {
            try
            {
                //创建一个Socket对象
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //设置指定的端口号和服务器的IP地址
                IPAddress ip = IPAddress.Parse(tbx_IP.Text);
                IPEndPoint endpoint = new IPEndPoint(ip, Convert.ToInt32(tbx_port.Text));

                //绑定IPEndPoint
                socketWatch.Bind(endpoint);
                ShowMsg("监听成功");

                //设置监听20个客户端服务器：
                socketWatch.Listen(20);

                //创建线程用来监听;
                //线程创建方法：Thread th = new Thread(Listen);  
                //其中listen为方法名 即实例化
                th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);    //Start里面的参数 是线程方法的参数
                btn_start.Enabled = false;
                btn_end.Enabled = true;
            }
            catch
            {
                ShowMsg("再来一次吧，操作失误了");
            }
        }
        /// <summary>
        /// TCP相关函数设定
        /// </summary>
        Socket socketSend;
        string ipAddress;
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        Socket socketWatch = null;
        Thread th = null;
        string defaultfilePath, path;//路径
        private List<string> ImageType;//用于保存load图片的格式
        ArrayList TCP_message_save = new ArrayList();//用于保存listview数据时用的数组
        void ShowMsg(string str)//log
        {
            frmMain.frmain.textBox1.AppendText(str + "\r\n");//--------------------------------
        }
        void Listen(Object o)// 等待客户端的连接 并且创建与之通信用的Socket
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                try
                {
                    //创建一个新的用于与客户端进行通信的socket对象
                    socketSend = socketWatch.Accept();
                    ipAddress = socketSend.RemoteEndPoint.ToString();   //获得客户端的ip地址和端口号  ipAddress格式例如：127.0.0.1:8888

                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    //192.168...连接成功
                    ShowMsg(ipAddress + ":" + "连接成功");
                    //创建一个新的线程，用来不停的接收客户端发送过来的消息
                    Thread th = new Thread(Recive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch
                {

                }
            }
        }
        void Recive(object o)// 接收消息
        {
            Socket socketSend = o as Socket;
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 10];   //设置缓存大小
                    int r = socketSend.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    string s = Encoding.UTF8.GetString(buffer, 0, r);
                    if (s == "\u0002SP,C,,,1,01,03,1\u0003")//开电
                    {
                        sendstring("\u0002CP,S,0,1,1,1,3\u0003\u0002SP,S,0,1,1,1,3\u0003\u0002CP,S,0,1,1,1,ALL\u0003");
                    }
                    if (s == "\u0002SP,C,,,1,01,03,0\u0003")//关电
                    {
                        sendstring("\u0002SP,S,0,0,1,1,3\u0003");
                    }
                    if (s.Contains(".lua"))//带有JC脚本指令
                    {
                        sendstring("\u0002TBC, S, 0,, 0, 1, 1, 3\u0003");
                        sendstring("\u0002PC,S,0,,1,1\u0003");//PG in place
                    }
                    if (s.Contains("\u0002CP,C,,,1,01,03,"))//切图
                    {
                        string alpha = ((char)buffer[16]).ToString();
                        string alpha1 = "";
                        if (buffer[18] != 0)
                        {
                            alpha1 = ((char)buffer[17]).ToString();
                            alpha = alpha + alpha1;
                        }
                        int num = Convert.ToInt32(alpha, 16);
                        if (num <= list_tcp_bmp.Items.Count)
                        {
                            if (!frmMain.frmain.comPort.IsOpen)//确认串口打开情况
                            {
                                try
                                {
                                    frmMain.frmain.comPort.PortName = Detection.GetComNum();
                                    frmMain.frmain.comPort.BaudRate = Setting.ComSet.comBaudRate;
                                    frmMain.frmain.openSerialPort(true);
                                }
                                catch
                                {
                                    ShowMsg("串口状态异常，请重试");
                                    return;
                                }
                            }
                            if (list_tcp_bmp.Items[num - 1].SubItems[3].Text == "否")
                            {
                                try
                                {
                                    FileInfo fi = new FileInfo(tbx_tcp_bmp_address.Text + "\\" + list_tcp_bmp.Items[num - 1].SubItems[1].Text);//JC发过来的图片序号1对应列表中的0
                                    frmMain.MyImage ss = new frmMain.MyImage(fi.FullName);
                                    frmMain.frmain.loadimage(ss);
                                }
                                catch
                                {
                                    ShowMsg(list_tcp_bmp.Items[num - 1].SubItems[1].Text + "图片不存在");
                                }
                            }
                            else
                            {
                                frmMain.frmain.checkBox1.Checked = false;
                                string[] tcp_fpga_bmp_B = list_tcp_bmp.Items[num - 1].SubItems[1].Text.Split('B');
                                frmMain.frmain.numPatternB.Value = Convert.ToInt16(tcp_fpga_bmp_B[1]);
                                string[] tcp_fpga_bmp_G = tcp_fpga_bmp_B[0].Split('G');
                                frmMain.frmain.numPatternG.Value = Convert.ToInt16(tcp_fpga_bmp_G[1]);
                                string tcp_fpga_bmp_R = tcp_fpga_bmp_G[0].Remove(0, 1);
                                frmMain.frmain.numPatternR.Value = Convert.ToInt16(tcp_fpga_bmp_R);
                                frmMain.frmain.OLED_Show_Click(frmMain.frmain.btnPatternW, null);
                            }
                        }
                        else
                        {
                            MessageBox.Show("照片数目不匹配");
                        }
                    }
                    if (s == "\u0002RHVD,C,2,1,1,01,03,0.00,0.00,1\u0003")
                    {
                        sendstring("\u0002RHVD,S,0,,1,01,03\u0003");
                        sendstring("\u0002TPS,S,0,0,1,1,3\u0003");
                    }
                    ShowMsg(socketSend.RemoteEndPoint + ":" + s);
                }
            }
            catch
            {
                sendstring("\u0002SP,S,0,0,1,1,3\u0003");//如遇异常，发送断电指令
                tbx_end_Click(null, null);
                MessageBox.Show("操作太快，慢点重来");
            }
        }
        private void sendstring(string text)//向客户端发送指令
        {
            try
            {
                string str = "";
                str = text;
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); //将字符串转成二进制格式字节
                List<byte> list = new List<byte>();
                /* list.Add(0);*/  //让客户端知道现在发送的文字
                list.AddRange(buffer);
                byte[] newBuffer = list.ToArray();
                dicSocket[ipAddress].Send(newBuffer);  //传输字符串到客户端
                //txt_Message.Text = "";
            }
            catch
            {
                ShowMsg("没有可发送信息");
            }
        }
        private void tbx_end_Click(object sender, EventArgs e)
        {
            try
            {
                if (th != null)
                {
                    socketWatch.Close();
                    th.Abort();
                    th = null;
                }
                socketWatch.Close();
                ShowMsg("关闭成功");
                //socketSend.Close();
                btn_end.Enabled = false;
                btn_start.Enabled = true;
            }
            catch
            {
                ShowMsg("你还是太年轻，操作失误了");
            }
        }
        private void CreateListItem_tcp(DirectoryInfo di)
        {
            int str = 0;
            string tcp_width;
            string tcp_heigth;
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem_tcp(childDi);
            }
            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.ImageIndex = str;
                    if (str < 10)
                    {
                        lvi.Text = "0" + str.ToString();//将序号加入第一列
                    }
                    else
                    {
                        lvi.Text = str.ToString();//将序号加入第一列
                    }
                    lvi.SubItems.Add(fi.Name);//将图片的名字加入第二列
                    Image pic = Image.FromFile(fi.FullName);//该图片的绝对路径
                    tcp_width = pic.Width.ToString();
                    tcp_heigth = pic.Height.ToString();
                    lvi.SubItems.Add(tcp_width + "X" + tcp_heigth);//将图片的分辨率加入第三列
                    lvi.SubItems.Add("否");//将是否FPGA刷图加入第四列
                    this.list_tcp_bmp.Items.Add(lvi);
                    str++;
                }
            }

        }
        private void AutoLIR_Load(object sender, EventArgs e)
        {
            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
        }
        private void btn_bmp_down_Click(object sender, EventArgs e)//图片列表中选中行下移
        {
            if (list_tcp_bmp.SelectedItems.Count > 0)
            {
                this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
                foreach (ListViewItem lvi in list_tcp_bmp.SelectedItems)  //选中项遍历 
                {
                    ListViewItem item = lvi;
                    int index = lvi.Index;
                    list_tcp_bmp.Items.RemoveAt(index);
                    if (index + 1 < list_tcp_bmp.Items.Count + 1)
                    {
                        list_tcp_bmp.Items.Insert(index + 1, item);
                    }
                    else
                    {
                        list_tcp_bmp.Items.Insert(0, item);
                    }
                }
                refresh_tcplist_num();//刷新图片序号
                this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
            }
            list_tcp_bmp.Focus();
        }
        private void btn_clear_list_Click(object sender, EventArgs e)//清空列表，保留表头
        {
            this.list_tcp_bmp.Items.Clear();
        }
        private void btn_bmp_new_Click(object sender, EventArgs e)//在列表中新建图，可以选择插入bmp或逻辑图，也可以选择是末尾添加还是中间插入
        {
            string tcp_width;
            string tcp_heigth;
            this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
            if (cbx_TCP_FPGA.Checked == true)
            {
                ListViewItem lva = new ListViewItem();
                lva.Text = "00";
                lva.SubItems.Add("R" + frmMain.frmain.numPatternR.Value.ToString() + "G" + frmMain.frmain.numPatternG.Value.ToString() + "B" + frmMain.frmain.numPatternB.Value.ToString());
                lva.SubItems.Add("FPGA");
                lva.SubItems.Add("是");
                if (cbx_bmp_insert.Checked == false)
                {
                    list_tcp_bmp.Items.Add(lva);
                }
                else
                {
                    foreach (ListViewItem lvi in list_tcp_bmp.SelectedItems)  //选中项遍历 
                    {
                        int index = lvi.Index;
                        list_tcp_bmp.Items.Insert(index, lva);
                    }
                }
            }
            else
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Filter = @"bmp|*.bmp;*.dsc|所有文件(*.*)|*.*"
                };
                openFileDialog.Multiselect = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    foreach (var FileName in openFileDialog.FileNames)
                    {
                        FileInfo fi = new FileInfo(FileName);
                        string filename = fi.Name;
                        Image img = Bitmap.FromFile(openFileDialog.FileName);
                        try
                        {
                            string adress = fi.FullName;
                            adress = adress.Replace(fi.Name, "");
                            adress = adress.Remove(adress.Length - 1, 1);
                            if (tbx_tcp_bmp_address.Text == "" || tbx_tcp_bmp_address.Text == adress)
                            {
                                tbx_tcp_bmp_address.Text = adress;
                            }
                            else
                            {
                                File.Copy(openFileDialog.FileName, tbx_tcp_bmp_address.Text + "\\" + fi.Name, true);
                            }
                        }
                        catch { MessageBox.Show("adress中已经存在同名图片，请确认"); };
                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = "00";
                        lvi.SubItems.Add(fi.Name);//将图片的名字加入第二列
                        Image pic = Image.FromFile(fi.FullName);//该图片的绝对路径
                        tcp_width = pic.Width.ToString();
                        tcp_heigth = pic.Height.ToString();
                        lvi.SubItems.Add(tcp_width + "X" + tcp_heigth);//将图片的分辨率加入第三列
                        lvi.SubItems.Add("否");//将是否FPGA刷图加入第四列
                        if (cbx_bmp_insert.Checked == false)
                        {
                            list_tcp_bmp.Items.Add(lvi);
                        }
                        else
                        {
                            foreach (ListViewItem lvii in list_tcp_bmp.SelectedItems)  //选中项遍历 
                            {
                                int index = lvii.Index;
                                list_tcp_bmp.Items.Insert(index, lvi);
                            }
                        }
                    }
                }
            }
            refresh_tcplist_num();//刷新图片序号
            this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }
        private void btn_bmp_up_Click(object sender, EventArgs e)//图片列表选中行上移
        {
            if (list_tcp_bmp.SelectedItems.Count > 0)
            {
                this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
                foreach (ListViewItem lvi in list_tcp_bmp.SelectedItems)  //选中项遍历 
                {
                    ListViewItem item = lvi;
                    int index = lvi.Index;
                    list_tcp_bmp.Items.RemoveAt(index);
                    if (!(index - 1 < 0))
                    {
                        list_tcp_bmp.Items.Insert(index - 1, item);
                    }
                    else
                    {
                        list_tcp_bmp.Items.Insert(list_tcp_bmp.Items.Count, item);
                    }
                }
                refresh_tcplist_num();//刷新图片序号
                this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
            }
            list_tcp_bmp.Focus();
        }
        private void btn_delete_rows_Click(object sender, EventArgs e)//删除选中行
        {
            this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
            foreach (ListViewItem lvi in list_tcp_bmp.SelectedItems)  //选中项遍历 
            {
                list_tcp_bmp.Items.RemoveAt(lvi.Index); // 按索引移除 
            }
            refresh_tcplist_num();//刷新图片序号
            this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }
        private void TCP_message_add(byte[] byteArray)//保存列表时将获取的byte数组转化为 ，间隔的字符串
        {
            string aaa = null;
            for (int i = 0; i < byteArray.Length; i++)
            {
                aaa = aaa + byteArray[i].ToString() + ",";
            }
            TCP_message_save.Add(aaa);
        }
        private void btn_save_list_Click(object sender, EventArgs e)
        {
            this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
            TCP_message_save.Clear();
            byte[] byteArray = System.Text.Encoding.Default.GetBytes(tbx_tcp_bmp_address.Text);
            TCP_message_save.Add(00);
            TCP_message_add(byteArray);
            for (int i = 0; i < list_tcp_bmp.Items.Count; i++)
            {
                byteArray = System.Text.Encoding.Default.GetBytes(list_tcp_bmp.Items[i].SubItems[0].Text + "?" + list_tcp_bmp.Items[i].SubItems[1].Text + "?" + list_tcp_bmp.Items[i].SubItems[2].Text + "?" + list_tcp_bmp.Items[i].SubItems[3].Text);
                TCP_message_add(byteArray);
            }
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = "Logic_Cfg File(*.ZCQ)|*.ZCQ";//定义保存的文件的类型
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                try
                {
                    for (int i = 0; i < TCP_message_save.Count; i++)     //IC 初始化代码
                    {
                        //string aaa = arrString[0].ToString();
                        //str = arrString[i].ToString();
                        sw.WriteLine(TCP_message_save[i].ToString());
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("图片列表保存成功");
                }
                catch
                {
                    MessageBox.Show("保存过程出错，请重试", "系统提示");
                }
            }
            this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }
        private void TCP_message_load(string byteArray, out string listview_text)//对一行载入的数据解析
        {
            string[] aaa = byteArray.Split(',');
            byte[] bbb = new byte[aaa.Length - 1];
            for (int i = 0; i < aaa.Length - 1; i++)
            {
                bbb[i] = byte.Parse(aaa[i]);
            }
            listview_text = System.Text.Encoding.Default.GetString(bbb);
        }
        private void btn_load_list_Click(object sender, EventArgs e)//载入列表信息
        {
            this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "Logic_Cfg File(*.ZCQ)|*.ZCQ";
            int count = 0;
            if (of.ShowDialog() == DialogResult.OK)
            {
                this.list_tcp_bmp.Items.Clear();
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                string buff_text;
                TCP_message_load(strLine, out buff_text);
                tbx_tcp_bmp_address.Text = buff_text;
                //循环读取文本信息
                while (!string.IsNullOrEmpty(strLine))
                {
                    TCP_message_load(strLine, out buff_text);
                    if (count < 2)
                    {
                        tbx_tcp_bmp_address.Text = buff_text;
                    }
                    else
                    {
                        string[] tcp_rows_text = buff_text.Split('?');
                        ListViewItem lva = new ListViewItem();
                        lva.Text = tcp_rows_text[0];
                        lva.SubItems.Add(tcp_rows_text[1]);
                        lva.SubItems.Add(tcp_rows_text[2]);
                        lva.SubItems.Add(tcp_rows_text[3]);
                        list_tcp_bmp.Items.Add(lva);
                    }
                    strLine = streamReader.ReadLine(); //循环读取下一行
                    count++;
                }
                fs.Close(); //关闭流
                streamReader.Close();
            }
            for (int i = 0; i < list_tcp_bmp.Items.Count; i++)
            {
                if (list_tcp_bmp.Items[i].SubItems[3].Text == "否")
                {
                    if (!File.Exists(tbx_tcp_bmp_address.Text + "\\" + list_tcp_bmp.Items[i].SubItems[1].Text))
                    {
                        MessageBox.Show(tbx_tcp_bmp_address.Text + "路径下不存在" + list_tcp_bmp.Items[i].SubItems[1].Text);
                    }
                }
            }
            this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }
        private void btn_new_bmps_Click(object sender, EventArgs e)//批量插入逻辑图
        {
            this.list_tcp_bmp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控
            string[] bmps_new = tbx_newbmpslist.Text.Split(',');
            try
            {
                for (int i = 0; i < bmps_new.Length; i++)
                {
                    bmps_new[i].ToUpper();
                    ListViewItem lva = new ListViewItem();
                    lva.Text = "00";
                    if (bmps_new[i].Substring(0, 1) == "R")//识别首字母，判断灰阶设定
                    {
                        lva.SubItems.Add("R" + bmps_new[i].Remove(0, 1) + "G0" + "B0");
                        lva.SubItems.Add("FPGA");
                        lva.SubItems.Add("是");
                    }
                    else if (bmps_new[i].Substring(0, 1) == "G")
                    {
                        lva.SubItems.Add("R0" + "G" + bmps_new[i].Remove(0, 1) + "B0");
                        lva.SubItems.Add("FPGA");
                        lva.SubItems.Add("是");
                    }
                    else if (bmps_new[i].Substring(0, 1) == "B")
                    {
                        lva.SubItems.Add("R0" + "G0" + "B" + bmps_new[i].Remove(0, 1));
                        lva.SubItems.Add("FPGA");
                        lva.SubItems.Add("是");
                    }
                    else if (bmps_new[i].Substring(0, 1) == "W")
                    {
                        lva.SubItems.Add("R" + bmps_new[i].Remove(0, 1) + "G" + bmps_new[i].Remove(0, 1) + "B" + bmps_new[i].Remove(0, 1));
                        lva.SubItems.Add("FPGA");
                        lva.SubItems.Add("是");
                    }
                    else if (Regex.IsMatch(bmps_new[i], @"^[+-]?\d*[.]?\d*$"))//首字母识别不了,内容是数字
                    {
                        ListViewItem lvaR = new ListViewItem();
                        lvaR.Text = "00";
                        lvaR.SubItems.Add("R" + bmps_new[i] + "G0" + "B0");
                        lvaR.SubItems.Add("FPGA");
                        lvaR.SubItems.Add("是");
                        list_tcp_bmp.Items.Add(lvaR);

                        ListViewItem lvaG = new ListViewItem();
                        lvaG.Text = "00";
                        lvaG.SubItems.Add("R0" + "G" + bmps_new[i] + "B0");
                        lvaG.SubItems.Add("FPGA");
                        lvaG.SubItems.Add("是");
                        list_tcp_bmp.Items.Add(lvaG);

                        lva.SubItems.Add("R0" + "G0" + "B" + bmps_new[i]);
                        lva.SubItems.Add("FPGA");
                        lva.SubItems.Add("是");
                    }
                    else//格式错误
                    {
                        MessageBox.Show("输入格式有误");
                        break;
                    }
                    list_tcp_bmp.Items.Add(lva);
                }
            }
            catch
            {
                MessageBox.Show("输入数据格式有误，请输入R32或32 这样的。以,分隔");
            }
            refresh_tcplist_num();
            this.list_tcp_bmp.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }
        private void refresh_tcplist_num()//刷新列表序号
        {
            int tcplist_count = list_tcp_bmp.Items.Count;
            for (int i = 0; i < tcplist_count; i++)
            {
                if (i < 10)
                {
                    list_tcp_bmp.Items[i].SubItems[0].Text = "0" + i.ToString();
                }
                else
                {
                    list_tcp_bmp.Items[i].SubItems[0].Text = i.ToString();
                }
            }
        }
    }
}